package com.example.keli.base.utils;

import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 数字英文算一位，中文算两位
 * Created by jerry on 2019/1/8.
 */

public class MaxTextTwoLengthFilter implements InputFilter {

    private int mMaxLength;

    public MaxTextTwoLengthFilter(int maxLen){
        mMaxLength = maxLen;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart , int dend){
        // 判断是否到达最大长度
        int count = 0;
        // 之前就存在的内容
        int dindex = 0;
        while (count <= mMaxLength && dindex < dest.length()) {
            char c = dest.charAt(dindex++);
            if (c < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }
        if (count > mMaxLength) {
            return dest.subSequence(0, dindex - 1);
        }
        // 从编辑框刚刚输入进去的内容
        int sindex = 0;
        while (count <= mMaxLength && sindex < source.length()) {
            char c = source.charAt(sindex++);
            if (c < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }
        if (count > mMaxLength) {
            sindex--;
        }
        //过滤特殊字符,
        String regEx = "[,]";//这里可以添加需要的匹配符号
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(source.toString());
        if (matcher.matches()){
            return "";
        }else {
            return source.subSequence(0, sindex);
        }
    }

    /***
     * 匹配特殊字符，将其过滤
     * @param edit
     * @return
     */
    public String stringFilter(String edit) {
        String regEx = "[,]";//这里可以添加需要的匹配符号
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(edit);
        if (matcher.matches()){
            return "";
        }else {
            return null;
        }
    }
}